package com.example.demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", initParams = {
        @WebInitParam(name = "ENCODING", value = "UTF-8")
})
public class EncodingFilter implements Filter {

    private String ENCODING;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("EncodingFilter doFilter ENCODING:" + ENCODING);
        HttpServletRequest req = (HttpServletRequest) request;
        if ("GET".equals(req.getMethod())) {
            req = new EncodingWapper(req, ENCODING);
        } else {
            req.setCharacterEncoding(ENCODING);
        }
        chain.doFilter(req, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ENCODING = filterConfig.getInitParameter("ENCODING");
        System.out.println("EncodingFilter init ENCODING:" + ENCODING);
    }

    @Override
    public void destroy() {

    }
}
